import React, { Component } from 'react';
import styled from 'styled-components/native';
import { connect } from 'react-redux';
import { connectActionSheet } from '@expo/react-native-action-sheet';
import { withApollo } from 'react-apollo';

import { logout } from '../actions/user';
import Loading from '../components/Loading';
import { ToolbarButton } from '../components/common';
import { defaultAvatar } from '../utils/constants';

const AVATAR_SIZE = 30;
const AVATAR_RADIUS = AVATAR_SIZE / 2;

const Avatar = styled.Image`
  width: ${AVATAR_SIZE};
  height: ${AVATAR_SIZE};
  border-radius: ${AVATAR_RADIUS};
`;

class HeaderAvatar extends Component {

  _onHeaderAvatarPressed = () => {
    const options = ['Logout', 'Cancel'];
    const destructiveButtonIndex = 0;
    this.props.showActionSheetWithOptions({
      options,
      destructiveButtonIndex
    }, buttonIndex => {
      if (buttonIndex === 0) {
        this.props.client.resetStore();
        this.props.logout();
      }
    });
  }

  render() {
    if (!this.props.isAuthenticated) {
      return null;
    }
    const info = this.props.info;
    if (!info) {
      return (
        <ToolbarButton disabled>
          <Loading size="small" />
        </ToolbarButton>
      );
    }
    return (
      <ToolbarButton onPressed={() => this._onHeaderAvatarPressed()}>
        <Avatar source={{ uri: info.avatar || defaultAvatar }} />
      </ToolbarButton>
    );
  }
}

const mapStateToProps = (state) => ({
  info: state.user.info,
  isAuthenticated: state.user.isAuthenticated
});

export default withApollo(
  connect(mapStateToProps, { logout })(connectActionSheet(HeaderAvatar))
);
